package pl.register.android.database.crud;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import pl.register.android.database.tables.HomeworkTopicDBTable;
import pl.register.android.homework.HomeworkTopic;
import pl.register.android.lesson.LessonProgram;

/**
 * @author Mateusz Strzelecki
 * @since 2013-04-26
 */
public class HomeworkTopicCRUD {

    private SQLiteDatabase database;

    public HomeworkTopicCRUD(SQLiteDatabase database) {
        this.database = database;
    }

    public HomeworkTopic findHomeworkTopicBy(LessonProgram lessonProgram) {
        HomeworkTopic homework = null;
        String where = HomeworkTopicDBTable.FK_LESSON_PROGRAM_ID + " = " + lessonProgram.getId();
        Cursor cursor = database.query(HomeworkTopicDBTable.TABLE_NAME, null, where, null, null, null, null);
        if (cursor.moveToFirst()) {
            Long homeworkId = cursor.getLong(cursor.getColumnIndex(HomeworkTopicDBTable.ID));
            String homeworkTopic = cursor.getString(cursor.getColumnIndex(HomeworkTopicDBTable.TOPIC));
            int homeworkIsDoneInt = cursor.getInt(cursor.getColumnIndex(HomeworkTopicDBTable.IS_DONE));
            homework = new HomeworkTopic(homeworkId, homeworkTopic, homeworkIsDoneInt == 1);
        }
        cursor.close();
        return homework;
    }

    public HomeworkTopic insertHomeworkTopic(HomeworkTopic homeworkTopic, LessonProgram lessonProgram) {
        ContentValues insertValues = new ContentValues();
        insertValues.put(HomeworkTopicDBTable.TOPIC, homeworkTopic.getTopic());
        insertValues.put(HomeworkTopicDBTable.IS_DONE, homeworkTopic.isDone());
        insertValues.put(HomeworkTopicDBTable.FK_LESSON_PROGRAM_ID, lessonProgram.getId());
        long rowId = database.insert(HomeworkTopicDBTable.TABLE_NAME, null, insertValues);
        homeworkTopic.setId(rowId);
        return homeworkTopic;
    }

    public HomeworkTopic updateHomeworkTopic(HomeworkTopic homework) {
        String where = HomeworkTopicDBTable.ID + " = " + homework.getId();
        ContentValues updateValues = new ContentValues();
        updateValues.put(HomeworkTopicDBTable.TOPIC, homework.getTopic());
        updateValues.put(HomeworkTopicDBTable.IS_DONE, homework.isDone());
        database.update(HomeworkTopicDBTable.TABLE_NAME, updateValues, where, null);
        return homework;
    }

}